<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '首页',
  },
}
</route>
<template>
  <view class="bg-white overflow-hidden pt-2 px-4">
    <view class="mt-8">
      <image src="/static/logo.png" alt="" class="w-28 h-28 block mx-auto" />
    </view>
    <view class="text-center text-4xl mt-4">账号密码登录</view>
    <view class="text-center text-1xl mt-2 mb-6">请使用您的账号密码</view>

    <wd-form ref="form" :model="formData">
      <wd-cell-group border>
        <wd-input
          label="账号"
          label-width="150rpx"
          prop="account"
          clearable
          v-model="formData.account"
          placeholder="请输入您的账号"
          prefixIcon="user"
          :rules="[
            { required: false, pattern: /^[a-zA-Z0-9]{1,20}$/, message: '请填写正确的用户名' },
          ]"
        />
        <wd-input
          label="密码"
          label-width="150rpx"
          prop="password"
          clearable
          show-password
          v-model="formData.password"
          placeholder="请输入6-12位密码"
          prefixIcon="lock-on"
          :rules="[{ required: false, pattern: /^.{6,12}$/, message: '密码长度为6-12位' }]"
        />
      </wd-cell-group>
      <view class="footer mt-8">
        <wd-button type="primary" :round="false" size="large" @tap="handleSubmit" block>
          登录
        </wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useToast } from 'wot-design-uni'
import LoginApi from '@/api/api'
import { initUnitConfig } from '@/utils/unit'

const toast = useToast()
defineOptions({
  name: 'Home',
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 定义登录表单
const form = ref()
const formData = reactive<{
  // 账号
  account: string
  // 密码
  password: string
}>({
  account: '',
  password: '',
})

const handleSubmit = () => {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      console.log(valid, errors)

      if (valid) {
        console.log(formData, '表单数据')
        LoginApi.login({
          ...formData,
          inputCode: '1815',
          code: '6E22BF6D34D675898FF7C9F82ECAFBA5',
          device: 'pda',
        })
          .then((res) => {
            console.log(res)
            initUnitConfig()
            toast.success({
              msg: '登录成功',
              closed() {
                uni.redirectTo({
                  url: `/pages/index/index`,
                })
              },
            })
          })
          .catch((err) => {
            console.log(err, '登录失败')
          })
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

onLoad(() => {
  // getCaptchaCode()
})
</script>

<style>
.main-title-color {
  color: #d14328;
}
</style>
